package com.house.schedule;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.house.entity.Message;
import com.house.entity.Order;
import com.house.service.MessageService;
import com.house.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 提醒消息定时器
 */
@Component
@Slf4j
public class MessageSchedule {


    @Autowired
    OrderService orderService;

    @Autowired
    MessageService messageService;


    /**
     * 定时任务 每五分钟一执行
     */
    @Scheduled(cron = "*/30 * * * * ?")
//    @Scheduled(cron = "0 */5 * * * ?")
    public void process() {

        DateTime dateTime = DateUtil.offsetMonth(DateUtil.date(), 12);

        List<Order> orders = orderService.list(Wrappers.<Order>query()
                .eq("remind", "0").le("check_out_time", dateTime.toDateStr()));

        log.info("扫描即将到期订单信息, 对一个月内到期的订单发送消息提醒。 本次提醒数： {}", orders.size());

        orders.forEach(order -> {
            Message message = new Message();
            message.init();
            message.setTitle("到期提醒");
            message.setExpTime(order.getCheckOutTime());
            message.setUserId(order.getCreateUser());
            message.setUsername(order.getUsername());
            message.setContent(String.format("您的房屋即将到期，请及时续租！ 到期时间： %s", order.getCheckOutTime()));
            messageService.saveOrUpdate(message);

            order.setRemind("1");
            orderService.saveOrUpdate(order);
        });
    }
}
